<template>
  <div class="court-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input
            v-model="queryParams.name"
            placeholder="场地名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            style="width: 192px"
            v-model="queryParams.status"
            placeholder="场地状态"
            clearable
          >
            <el-option label="启用" :value="1" />
            <el-option label="维护中" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="top-actions">
        <el-button type="primary" @click="handleAdd">新增场地</el-button>
      </div>

      <el-table
        :data="courtList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="name" label="场地名称" />
        <el-table-column prop="price" label="每半小时价格" width="120">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="status" label="场地状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? "启用" : "维护中" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" />
        <el-table-column prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? "设为维护" : "设为启用" }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑场地对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="courtFormRef"
        :model="courtForm"
        :rules="courtRules"
        label-width="100px"
      >
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="courtForm.name" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="每半小时价格" prop="price">
          <el-input-number
            v-model="courtForm.price"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="场地状态" prop="status">
          <el-radio-group v-model="courtForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">维护中</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getCourtList,
  saveCourt,
  deleteCourt,
  updateCourtStatus,
  deleteCourtByPost,
} from "@/api/court";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
  status: "",
});

const loading = ref(false);
const total = ref(0);
const courtList = ref([]);

// 场地表单
const dialogVisible = ref(false);
const dialogTitle = ref("");
const courtFormRef = ref();
const courtForm = reactive({
  id: undefined,
  name: "",
  price: 0,
  status: 1,
});

// 表单校验规则
const courtRules = {
  name: [{ required: true, message: "请输入场地名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入每半小时价格", trigger: "blur" }],
};

// 查询场地列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getCourtList(queryParams);
    if (res.code === 200) {
      courtList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "获取场地列表失败");
    }
  } catch (error) {
    console.error("获取场地列表出错:", error);
    ElMessage.error("获取场地列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮
const resetQuery = () => {
  queryParams.name = "";
  queryParams.status = "";
  handleQuery();
};

// 新增场地
const handleAdd = () => {
  resetCourtForm();
  dialogTitle.value = "新增场地";
  dialogVisible.value = true;
};

// 编辑场地
const handleEdit = (row) => {
  resetCourtForm();
  dialogTitle.value = "编辑场地";
  courtForm.id = row.id;
  courtForm.name = row.name;
  courtForm.price = row.price;
  courtForm.status = row.status;
  dialogVisible.value = true;
};

// 删除场地
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该场地吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 使用POST方式删除（兼容接口）
        const res = await deleteCourtByPost(row.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          getList();
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除场地出错:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 切换场地状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? "启用" : "维护中";

  ElMessageBox.confirm(`确认将该场地设为${statusText}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updateCourtStatus(row.id, newStatus);
        if (res.code === 200) {
          ElMessage.success("设置成功");
          getList();
        } else {
          ElMessage.error(res.msg || "设置失败");
        }
      } catch (error) {
        console.error("更新场地状态出错:", error);
        ElMessage.error("设置失败");
      }
    })
    .catch(() => {});
};

// 重置场地表单
const resetCourtForm = () => {
  courtForm.id = undefined;
  courtForm.name = "";
  courtForm.price = 0;
  courtForm.status = 1;
};

// 提交表单
const submitForm = () => {
  courtFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await saveCourt(courtForm);
        if (res.code === 200) {
          ElMessage.success(courtForm.id ? "修改成功" : "新增成功");
          dialogVisible.value = false;
          getList();
        } else {
          ElMessage.error(res.msg || "操作失败");
        }
      } catch (error) {
        console.error("保存场地出错:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 分页
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.court-container {
  padding: 10px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .top-actions {
      margin-bottom: 20px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
